import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import {
  getToken
} from '@/utils/auth' // 验权
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // 免登陆 白名单
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  //登陆写的cookie 判断是否已登陆
  console.log("1")
  if (getToken()) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      // 获取用户信息
      console.log("1")
      console.log(store.getters.name)
      if (store.getters.name === '') {
        store.dispatch('getUserInfo').then(res => { // 拉取用户信息
          next()
        })
        .catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error('验证失败，请重新登陆')
            next({
              path: '/login'
            })
          })
        })
      } else {
        next()
      }
    }
  } else {
    //白名单
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})
